package main

import (
	"fmt"
	"net"
	"strings"
)

func main() {
	fmt.Println("获取本机IP")
	GetInternalIp()
	fmt.Println("获取本机所在外网IP")
	ip, err := GetOutBoundIP()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(ip)
}

func GetInternalIp()  {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		fmt.Println("net.Interfaces failed, err:", err.Error())
		return
	}

	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags & net.FlagUp) != 0 {
			address, _ := netInterfaces[i].Addrs()
			for _, address := range address {
				if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						fmt.Println(ipnet.IP.String())
						return
					}
				}
			}
		}
	}

	return
}

func GetOutBoundIP()(ip string, err error)  {
	conn, err := net.Dial("udp", "255.255.255.255:53")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("remote addr",conn.RemoteAddr().String())

	localAddr := conn.LocalAddr().(*net.UDPAddr)
	ip = strings.Split(localAddr.String(), ":")[0]
	return
}